package com.xzy;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.InlineShardingStrategyConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
import org.apache.shardingsphere.shardingjdbc.api.yaml.YamlShardingDataSourceFactory;

import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 数据分片配置类
 *
 * @author xzy.xiao
 * @date 2022/8/10  9:35
 */
public class ShardingConfig {

    /**
     * 基于Java编码配置分片规则
     */
    public static DataSource configWithJava() throws SQLException {
        // 数据源
        Map<String, DataSource> dataSourceMap = new HashMap<>(2);

        BasicDataSource dataSource0 = new BasicDataSource();
        dataSource0.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource0.setUrl("jdbc:mysql://127.0.0.1:3306/db0?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false");
        dataSource0.setUsername("root");
        dataSource0.setPassword("123456");
        dataSourceMap.put("db0", dataSource0);

        BasicDataSource dataSource1 = new BasicDataSource();
        dataSource1.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource1.setUrl("jdbc:mysql://127.0.0.1:3306/db1?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false");
        dataSource1.setUsername("root");
        dataSource1.setPassword("123456");
        dataSourceMap.put("db1", dataSource1);

        // 分片规则
        ShardingRuleConfiguration shardingRuleConfiguration = new ShardingRuleConfiguration();

        TableRuleConfiguration tableRuleConfiguration = new TableRuleConfiguration("tbl_order", "db${0..1}.tbl_order${0..1}");
        tableRuleConfiguration.setDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("order_no", "db${order_no % 2}")); // 水平分库
        tableRuleConfiguration.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("user_no", "tbl_order${user_no % 2}")); // 水平分表

        shardingRuleConfiguration.getTableRuleConfigs().add(tableRuleConfiguration);

        // Create sharding data source.
        return ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfiguration, new Properties());
    }

    /**
     * 基于Yaml文件配置分片规则
     */
    public static DataSource configWithYaml() throws SQLException, IOException {
        URL url = ShardingConfig.class.getClassLoader().getResource("sharding.yaml");
        File yamlFile = new File(url.getFile());
        return YamlShardingDataSourceFactory.createDataSource(yamlFile);
    }
}
